<template>
    <div>
        <improve-ground v-if="$store.state.pk.status === 'matching'"/>
        <PlayGround v-if="$store.state.pk.status === 'playing'"/>
    </div>
</template>

<script>
import PlayGround from "@/components/PlayGround.vue"
import ImproveGround from "@/components/ImproveGround.vue"
import {onMounted,onUnmounted} from "vue"
import {useStore} from "vuex"
import {GamePiece} from "@/assets/scripts/GamePiece"
export default {
  components:{
    PlayGround,
    ImproveGround
  },
  setup(){
    const store = useStore();
    let socket = null;

    //开始之前先清空一下状态
    store.commit("updateLoser","none");
    store.commit("updateIsRecord",false);
    store.commit("updatePlayer",1);

    let socketUrl = `ws://127.0.0.1:3000/websocket/${store.state.user.token}/`;
    socket = new WebSocket(socketUrl);

    store.commit("updateOpponent",{
        username:"我的对手",
        photo:"https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png",
    });

    onMounted(() =>{
        socket.onopen = ()=>{
            console.log("Connected!");
            store.commit("updateSocket",socket);
        },
        socket.onmessage = (msg) =>{
            const data = JSON.parse(msg.data);
            if(data.event === "start-matching"){
                setTimeout( ()=>{ 
                    store.commit("updateStatus","playing");
                },200)
                store.commit("updateGame",data.game);
            }else if(data.event === "move"){
                const game = store.state.pk.gameObject;
                if(data.currentPlayer === "1"){
                    new GamePiece({id:store.state.user.id,c:data.col,r:data.row,color:"#000000"},game);
                    store.commit("updatePlayer","2");
                }else{
                    new GamePiece({id:store.state.user.id,c:data.col,r:data.row,color:"#FFFFFF"},game);
                    store.commit("updatePlayer","1");
                }
            
            }else if(data.event === "result"){
                console.log(data);//这个后端传来游戏结束，设置游戏状态，并且弹出提示框
                store.commit("updateLoser",data.loser)
                store.commit("updatePlayer","1"); //不管谁赢，设置初始状态
            }
        }
        
    });
    onUnmounted( () =>{
        socket.close(); //断开链接
    })
  }
}
</script>

<style>

</style>
